#!/usr/bin/env python3
"""
CoordinationEngine参数问题诊断脚本

用于验证CoordinationEngine初始化参数问题的诊断和修复效果
"""

import sys
import os
import asyncio
import traceback
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

def print_section(title: str):
    """打印分节标题"""
    print(f"\n{'='*60}")
    print(f"🔍 {title}")
    print('='*60)

def print_result(test_name: str, success: bool, details: str = ""):
    """打印测试结果"""
    status = "✅ 成功" if success else "❌ 失败"
    print(f"{status} {test_name}")
    if details:
        print(f"   详情: {details}")

async def test_coordination_engine_import():
    """测试CoordinationEngine导入"""
    print_section("测试CoordinationEngine导入")
    
    try:
        from aiquant.coordination.coordination_engine import CoordinationEngine
        print_result("CoordinationEngine导入", True)
        
        # 检查构造函数签名
        import inspect
        sig = inspect.signature(CoordinationEngine.__init__)
        params = list(sig.parameters.keys())
        print(f"📋 构造函数参数: {params}")
        
        # 检查是否需要agent_registry参数
        if 'agent_registry' in params:
            print_result("agent_registry参数检查", True, "构造函数确实需要agent_registry参数")
            return True, "需要agent_registry参数"
        else:
            print_result("agent_registry参数检查", False, "构造函数不需要agent_registry参数")
            return False, "不需要agent_registry参数"
            
    except Exception as e:
        print_result("CoordinationEngine导入", False, str(e))
        return False, str(e)

async def test_agent_registry_creation():
    """测试AgentRegistry创建"""
    print_section("测试AgentRegistry创建")
    
    try:
        from aiquant.agents.agent_registry import AgentRegistry
        agent_registry = AgentRegistry()
        print_result("AgentRegistry创建", True)
        
        # 检查可用方法
        methods = [method for method in dir(agent_registry) if not method.startswith('_') and callable(getattr(agent_registry, method))]
        print(f"📋 AgentRegistry可用方法: {methods[:10]}...")  # 只显示前10个
        
        return True, agent_registry
        
    except Exception as e:
        print_result("AgentRegistry创建", False, str(e))
        return False, str(e)

async def test_coordination_engine_without_params():
    """测试不带参数的CoordinationEngine创建（应该失败）"""
    print_section("测试不带参数的CoordinationEngine创建")
    
    try:
        from aiquant.coordination.coordination_engine import CoordinationEngine
        coordination_engine = CoordinationEngine()
        print_result("不带参数创建CoordinationEngine", False, "意外成功，这不应该发生")
        return False, "意外成功"
        
    except TypeError as e:
        if "missing" in str(e) and "agent_registry" in str(e):
            print_result("不带参数创建CoordinationEngine", True, f"正确失败: {e}")
            return True, str(e)
        else:
            print_result("不带参数创建CoordinationEngine", False, f"其他TypeError: {e}")
            return False, str(e)
    except Exception as e:
        print_result("不带参数创建CoordinationEngine", False, f"其他异常: {e}")
        return False, str(e)

async def test_coordination_engine_with_params():
    """测试带参数的CoordinationEngine创建（应该成功）"""
    print_section("测试带参数的CoordinationEngine创建")
    
    try:
        from aiquant.coordination.coordination_engine import CoordinationEngine
        from aiquant.agents.agent_registry import AgentRegistry
        
        # 创建AgentRegistry实例
        agent_registry = AgentRegistry()
        print_result("AgentRegistry创建", True)
        
        # 创建CoordinationEngine实例
        coordination_engine = CoordinationEngine(agent_registry)
        print_result("带参数创建CoordinationEngine", True)
        
        # 检查可用方法
        methods = [method for method in dir(coordination_engine) if not method.startswith('_') and callable(getattr(coordination_engine, method))]
        print(f"📋 CoordinationEngine可用方法: {methods[:10]}...")  # 只显示前10个
        
        # 检查是否有initialize方法
        if hasattr(coordination_engine, 'initialize'):
            print_result("initialize方法检查", True)
            await coordination_engine.initialize()
            print_result("initialize方法调用", True)
        else:
            print_result("initialize方法检查", False, "没有initialize方法")
        
        # 检查是否有close方法
        if hasattr(coordination_engine, 'close'):
            print_result("close方法检查", True)
            await coordination_engine.close()
            print_result("close方法调用", True)
        else:
            print_result("close方法检查", False, "没有close方法")
        
        return True, coordination_engine
        
    except Exception as e:
        print_result("带参数创建CoordinationEngine", False, str(e))
        traceback.print_exc()
        return False, str(e)

async def test_main_py_lifespan_issue():
    """测试main.py中的lifespan问题"""
    print_section("分析main.py中的lifespan问题")
    
    try:
        # 读取main.py文件
        with open('aiquant/main.py', 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 查找问题行
        lines = content.split('\n')
        problem_lines = []
        
        for i, line in enumerate(lines, 1):
            if 'CoordinationEngine()' in line and 'agent_registry' not in line:
                problem_lines.append((i, line.strip()))
        
        if problem_lines:
            print_result("发现问题行", True, f"找到{len(problem_lines)}个问题")
            for line_num, line_content in problem_lines:
                print(f"   第{line_num}行: {line_content}")
        else:
            print_result("发现问题行", False, "没有找到问题行")
        
        # 检查agent_registry是否在CoordinationEngine之前创建
        agent_registry_line = None
        coordination_engine_line = None
        
        for i, line in enumerate(lines, 1):
            if 'agent_registry = AgentRegistry()' in line:
                agent_registry_line = i
            if 'coordination_engine = CoordinationEngine()' in line:
                coordination_engine_line = i
        
        if agent_registry_line and coordination_engine_line:
            if agent_registry_line < coordination_engine_line:
                print_result("初始化顺序检查", True, f"AgentRegistry在第{agent_registry_line}行，CoordinationEngine在第{coordination_engine_line}行")
            else:
                print_result("初始化顺序检查", False, "初始化顺序错误")
        
        return True, problem_lines
        
    except Exception as e:
        print_result("分析main.py", False, str(e))
        return False, str(e)

async def generate_fix_suggestion():
    """生成修复建议"""
    print_section("修复建议")
    
    print("🔧 修复方案:")
    print("1. 将main.py第68行的:")
    print("   coordination_engine = CoordinationEngine()")
    print("   修改为:")
    print("   coordination_engine = CoordinationEngine(agent_registry)")
    print()
    print("2. 确保agent_registry在第55行已正确创建:")
    print("   agent_registry = AgentRegistry()")
    print()
    print("3. 修复后的代码应该是:")
    print("   # 第55行")
    print("   agent_registry = AgentRegistry()")
    print("   # ... 其他代码 ...")
    print("   # 第68行")
    print("   coordination_engine = CoordinationEngine(agent_registry)")

async def main():
    """主函数"""
    print("🚀 开始CoordinationEngine参数问题诊断")
    print(f"⏰ 诊断时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 测试结果统计
    test_results = []
    
    # 1. 测试CoordinationEngine导入和参数检查
    success, details = await test_coordination_engine_import()
    test_results.append(("CoordinationEngine导入和参数检查", success))
    
    # 2. 测试AgentRegistry创建
    success, details = await test_agent_registry_creation()
    test_results.append(("AgentRegistry创建", success))
    
    # 3. 测试不带参数的CoordinationEngine创建
    success, details = await test_coordination_engine_without_params()
    test_results.append(("不带参数创建CoordinationEngine", success))
    
    # 4. 测试带参数的CoordinationEngine创建
    success, details = await test_coordination_engine_with_params()
    test_results.append(("带参数创建CoordinationEngine", success))
    
    # 5. 分析main.py中的问题
    success, details = await test_main_py_lifespan_issue()
    test_results.append(("main.py问题分析", success))
    
    # 6. 生成修复建议
    await generate_fix_suggestion()
    
    # 总结
    print_section("诊断结果总结")
    successful_tests = sum(1 for _, success in test_results if success)
    total_tests = len(test_results)
    
    for test_name, success in test_results:
        print_result(test_name, success)
    
    print(f"\n📊 诊断成功率: {successful_tests}/{total_tests} ({successful_tests/total_tests*100:.1f}%)")
    
    if successful_tests >= 4:  # 至少4个测试成功
        print("🎉 诊断完成！问题确认：CoordinationEngine需要agent_registry参数")
        print("💡 建议：按照上述修复方案修改main.py文件")
    else:
        print("⚠️ 诊断发现多个问题，需要进一步调查")

if __name__ == "__main__":
    asyncio.run(main())